package com.payment.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * Md5加密方法
 *
 * @author payment
 */
public class Md5Utils {
    private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);

    private static byte[] md5(String s) {

        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        } catch (Exception e) {
            log.error("MD5 Error...", e);
        }
        return null;
    }

    private static final String toHex(byte[] hash) {
        if (hash == null) {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++) {
            if ((hash[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s) {
        try {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        } catch (Exception e) {
            log.error("not supported charset...{}", e);
            return s;
        }
    }

    /**
     * 签名
     *
     * @param SortedMap
     * @param md5Key    注意md5key各家不同
     * @return
     */
    public static String signData(Map<String, String> SortedMap, String md5Key) {
        List<String> stringSort = new ArrayList<String>();

        for (java.util.Map.Entry<String, String> entry : SortedMap.entrySet()) {
            if (entry.getValue() != null && !"".equals(entry.getValue())
                    && !"null".equals(entry.getValue()) && !entry.getKey().equals("sign")
                    && !entry.getKey().equals("pl_sign")) {
                stringSort.add(entry.getKey());
            }
        }
        Collections.sort(stringSort, Collator.getInstance(Locale.CHINA));//排序
        StringBuffer signDatas = new StringBuffer();
        for (int i = 0; i < stringSort.size(); i++) {
            signDatas.append(SortedMap.get(stringSort.get(i)));
        }
        signDatas.append(md5Key);
        String sign = encrypt2MD5(signDatas.toString());
        return sign;
    }

    public static HashMap<String, String> parseCipherResponseData(String responseData) {
        HashMap<String, String> map = new HashMap<String, String>(16);
        String[] s1 = responseData.split("&");
        String[] s2 = new String[2];
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s1.length; i++) {
            s2 = s1[i].split("=", 2);
            map.put(s2[0], s2[1]);
            if (!s2[0].equals("sign")) {
                sb.append(s2[0] + "=" + s2[1] + "&");
            }
        }
        String source = sb.substring(0, sb.length() - 1);
        map.put("source", source);
        return map;
    }

    public static String signDataTianXia(Map<String, String> SortedMap, String md5Key, String publicKey) throws UnsupportedEncodingException, Exception {
        List<String> stringSort = new ArrayList<String>();
        for (java.util.Map.Entry<String, String> entry : SortedMap.entrySet()) {
            if (entry.getValue() != null && !"".equals(entry.getValue())
                    && !"null".equals(entry.getValue()) && !entry.getKey().equals("sign")
                    && !entry.getKey().equals("pl_sign")) {
                stringSort.add(entry.getKey());
            }
        }
        Collections.sort(stringSort, Collator.getInstance(Locale.CHINA));//排序
        StringBuffer signDatas = new StringBuffer();
        for (int i = 0; i < stringSort.size(); i++) {
            signDatas.append(stringSort.get(i) + "=" + SortedMap.get(stringSort.get(i)) + "&");
        }
        signDatas.append("key" + "=" + md5Key);
        String sign = encrypt2MD5(signDatas.toString());
        signDatas.append("&sign=" + sign);
        String cdata = signDatas.toString();
        log.info("天下上送数据：" + cdata);
        String s = RSAUtil.encryptByPublicKey(cdata.getBytes("UTF-8"), publicKey);
        return s;
    }

    public final static String md51(String paramSrc) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = paramSrc.getBytes("UTF-8");
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str).toLowerCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encrypt2MD5(String originstr) {
        String result = null;
        // 用来将字节转换成 16 进制表示的字符
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};
        if (originstr != null && !"".equals(originstr)) {
            try {
                // 返回实现指定摘要算法的 MessageDigest 对象
                MessageDigest md = MessageDigest.getInstance("MD5");
                // 使用utf-8编码将originstr字符串编码并保存到source字节数组
                byte[] source = originstr.getBytes("utf-8");
                // 使用指定的 byte 数组更新摘要
                md.update(source);
                // 通过执行诸如填充之类的最终操作完成哈希计算,结果是一个128位的长整数
                byte[] tmp = md.digest();
                // 用16进制数表示需要32位
                char[] str = new char[32];
                for (int i = 0, j = 0; i < 16; i++) {
                    // j表示转换结果中对应的字符位置
                    // 从第一个字节开始,对 MD5 的每一个字节
                    // 转换成 16 进制字符
                    byte b = tmp[i];

                    // 取字节中高 4 位的数字转换
                    // 无符号右移运算符>>> ,它总是在左边补0
                    // 0x代表它后面的是十六进制的数字. f转换成十进制就是15
                    str[j++] = hexDigits[b >>> 4 & 0xf];

                    // 取字节中低 4 位的数字转换
                    str[j++] = hexDigits[b & 0xf];
                }

                // 结果转换成字符串用于返回
                result = new String(str);

            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }

        return result;
    }


    public static void main(String[] args) throws IOException {
        String name = "付志莉";
        name=name.replaceAll(name.substring(1,name.length()-1),"*");
        System.out.println(name);

    }


}

